package arithmetic.socket.nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * nio方式读写文件
 * @author jiangfeng
 * Created on 2020-03-24
 */
public class NioTest2 {
    public static void main(String[] args) throws Exception {

        FileInputStream fileInputStream = new FileInputStream("src/main/java/arithmetic/socket/nio/inputStream.txt");
        FileChannel inputChannel = fileInputStream.getChannel();
        FileOutputStream fileOutputStream = new FileOutputStream("src/main/java/arithmetic/socket/nio/outStream.txt");
        FileChannel outputChannel = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        while (true) {
            // 如果注释此行 则死循环 read一直为0
            byteBuffer.clear();
            int read = inputChannel.read(byteBuffer);
            System.out.println(read);
            if(read == -1){
                break;
            }
            byteBuffer.flip();
            outputChannel.write(byteBuffer);
        }
        inputChannel.close();
        outputChannel.close();

    }
}
